import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import { connect } from '@tarojs/redux'
import { AtDrawer } from 'taro-ui'

import { showMenuAction, changeMenuTitleAction, hideMenuAction } from '../../actions/menuAction'
import {checkUserLoginStatus} from '../../actions/userAction'
import './index.scss'

@connect((store) => {
  return {...store.menuReducer, user: store.userReducer} 
}, (dispatch) => ({
  onShowMenuAll(){
    dispatch(showMenuAction())
  },
  onChangeMenuTitle(cate){
    dispatch(changeMenuTitleAction(cate))
  },
  onHideMenu(){
    dispatch(hideMenuAction())
  }
}))

class Menu extends Component{
  handleShowMenu(){
    this.props.onShowMenuAll()
  }

  getMenuItems(data){
    return data.map(item => item.value
  )}

  clickMenuItem(index){
    let {list} = this.props
    let currentClickItem = list[index]
    if(currentClickItem.key !== this.props.list.key){
      this.props.onChangeMenuTitle(currentClickItem)
    }
  }

  closeMenu(){
    this.props.onHideMenu()
  }

  redirectLogin(){
    let {user} = this.props
    checkUserLoginStatus(user).then(res => {
      if(res){
        Taro.navigateTo({url: '/pages/user/index'})
      }else{
        Taro.navigateTo({url: '/pages/login/index'})
      }
    })
  }

  render(){
    let {currentListItem, showMenu, list} = this.props
    let items = this.getMenuItems(list)
    return(
      <View className='menu-container'>
        <AtDrawer 
          style='position: absolute;' 
          show={showMenu}
          mask
          items={items}
          onItemClick={this.clickMenuItem.bind(this)}
          onClose={this.closeMenu.bind(this)}
        />
        <Image onClick={this.handleShowMenu.bind(this)} className='menu-icon menu-icon-left' src={require('../../assets/images/menu.png')} />
        <Text className='menu-text'>{currentListItem ? currentListItem.value : ''}</Text>
        <Image onClick={this.redirectLogin.bind(this)} className='menu-icon menu-icon-right' src={require('../../assets/images/log-in.png')} />
      </View>
    )
  }
}

export default Menu